//
//  HCWThrowAnimation.m
//  LRShop
//
//  Created by HCW on 16/8/9.
//  Copyright © 2016年 HCW. All rights reserved.
//

#import "HCWThrowAnimation.h"

@implementation HCWThrowAnimation

- (void)beginThrowAnimationWithView:(UIView *)view
                          fromPoint:(CGPoint)fromPoint
                            toPoint:(CGPoint)toPoint
{
    self.showingView = view;
    UIBezierPath *path= [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(fromPoint.x, fromPoint.y)];
    //三点曲线
    [path addCurveToPoint:CGPointMake(toPoint.x+25, toPoint.y+25)
            controlPoint1:CGPointMake(fromPoint.x, fromPoint.y)
            controlPoint2:CGPointMake(fromPoint.x - 180, fromPoint.y - 200)];
    
    [self groupAnimation:path];
}

#pragma mark - 组合动画

-(void)groupAnimation:(UIBezierPath *)path
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    
    CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"alpha"];
    alphaAnimation.duration = 0.8f;
    alphaAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    alphaAnimation.toValue = [NSNumber numberWithFloat:0.1];
    alphaAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,alphaAnimation];
    groups.duration = 0.5f;
    groups.removedOnCompletion = NO;
    groups.fillMode = kCAFillModeForwards;
    groups.delegate = self;
    [groups setValue:@"groupsAnimation" forKey:@"animationName"];
    [self.showingView.layer addAnimation:groups forKey:@"position scale"];
}


- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(throwAnimation:didStop:)]) {
        [self.delegate throwAnimation:self didStop:flag];
    }
    self.showingView = nil;
}

@end
